package com.javasm.filter;

import com.javasm.domain.LoginUser;
import com.javasm.advice.AuthenExceptionAdvice;
import com.javasm.utlis.JwtUtil;
import com.javasm.utlis.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


/**
 * @Author：MoDebing
 * @Version：1.0
 * @Date：2022-09-01-19:34
 * @Description: 实现过滤器接口，不要实现默认的servlet过滤器接口 Filter
 * 因为在不同的servlet版本当中，一个请求可能会被调用多次
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final RedisCache redisCache;

    // 全局异常处理类
    private final AuthenExceptionAdvice authenExceptionAdvice;

    public JwtAuthenticationTokenFilter(RedisCache redisCache, AuthenExceptionAdvice authenExceptionAdvice){
        this.redisCache = redisCache;
        this.authenExceptionAdvice = authenExceptionAdvice;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取token,
        String token = request.getHeader("token");
        // 如果token为空，则进入方法体执行过滤器链，
        // 不为空则说明之前已经登陆过了，执行方法体下面的代码
        if (!StringUtils.hasText(token)){
            // 放行
            filterChain.doFilter(request,response);
            return;
        }

        // 解析token
        String parseUserId;
        try {
            Claims parseUserToken = JwtUtil.parseJWT(token);
            parseUserId = parseUserToken.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            authenExceptionAdvice.handlerRuntimeException(new RuntimeException("token非法,"+e.getMessage()),request,response);
            return;
        }
        String redisKey = "login:"+parseUserId;

        // 从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
            //authenExceptionAdvice.handlerRuntimeException(new RuntimeException("用户登录失效或者未登录"),request,response);
            //不往下执行程序了，也不放行
            return;
        }


        // 存入SecurityContextHolder
        // UsernamePasswordAuthenticationToken是 Authentication的实现
        //先封装
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request,response);
    }
}
